﻿using System;
using System.Reflection;
using System.Web;
using System.Web.UI;
using Cms.Data;
using Cms.Domain;
using Cms.Domain.RepositoryInterfaces;
using Cms.Utilities;
using Cms.Web.Framework.Controls;
using iLib.Web.UI;
using Page = Cms.Web.Framework.Controls.Page;

namespace Cms.Web.Framework.Plugins
{
    public abstract class BaseTemplatedPlugin : BasePlugin
    {
        private string _customParameters;
        private int _templateID;
        private BaseTemplatedPlugin _templateInstance;

        public int TemplateID
        {
            get { return _templateID; }
            set { _templateID = value; }
        }

        public string CustomParameters
        {
            get { return _customParameters; }
            set { _customParameters = value; }
        }

        public BaseTemplatedPlugin TemplateInstance
        {
            get { return _templateInstance; }
            set { _templateInstance = value; }
        }

        public string GetCustomParameterValue(string parameter)
        {
            if (_customParameters.Trim() == string.Empty)
                return string.Empty;
            foreach (string kvp in _customParameters.Split(";".ToCharArray()))
            {
                string key = HttpUtility.HtmlDecode(kvp.Substring(0, kvp.IndexOf("=")));
                if (key.ToLower() == parameter.ToLower())
                    return HttpUtility.HtmlDecode(kvp.Substring(kvp.IndexOf("=") + 1));
            }
            return string.Empty;
        }

        public virtual void OnPluginLoad(BaseTemplatedPlugin sender)
        {
        }
        
        protected void AddError(string message, string validationGroup)
        {
            (Page as Page).Presenter.AddValidationError(message, validationGroup);
        }
        
        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            if (_templateInstance == null)
            {
                return;
            }
            _templateInstance.OnPluginLoad(this);
        }

        protected override void CreateChildControls()
        {
            base.CreateChildControls();
            try
            {
                _templateInstance = (BaseTemplatedPlugin)Page.LoadControl("~/__System/PluginTemplates/" + _templateID + ".ascx");
                while (_templateInstance.Controls.Count > 0)
                {
                    Controls.Add(_templateInstance.Controls[0]);
                }
                _templateInstance.RequestDetails = this.RequestDetails;
                Translate();
            }
            catch (Exception ex)
            {
                Controls.Clear();
                Logging.LogError("BaseTemplatedPlugin", ex);
                throw;
            }
        }

        private void Translate()
        {
            ISystemRepository systemRepository = new SystemRepository();
            PluginTemplate template = systemRepository.GetPluginTemplate(_templateID);
            foreach (LocalizedPluginLiteral lpl in ControlFinder.FindControls(typeof(LocalizedPluginLiteral), this))
            {
                lpl.Text = template.GetLiteral(lpl.ID).GetHtml(RequestDetails.Locale.ID);
                if (string.IsNullOrEmpty(lpl.TiedControlID))
                    continue;
                Control tiedControl = FindControl(lpl.TiedControlID);
                if (tiedControl != null)
                {
                    Type type = tiedControl.GetType();
                    PropertyInfo pi = type.GetProperty(lpl.TiedProperty);
                    pi.SetValue(tiedControl, lpl.Text, null);
                }
                lpl.Visible = false;
            }
        }
    }
}